#include <iostream>
#include <chrono>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

using namespace std::chrono_literals;

class RobotObj
{
public:
    RobotObj() = default;
    ~RobotObj() = default;

    void setPub(const rclcpp::Publisher<std_msgs::msg::String>::SharedPtr &pub)
    {
        publisher_ = pub;
    }
    int getPubUseCount()
    {
        return publisher_.use_count();
    }

private:
    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_{};
};

class PublisherNode : public rclcpp::Node
{
public:
    PublisherNode(std::string name) : Node(name)
    {
        robot_obj_.setPub(this->create_publisher<std_msgs::msg::String>("topic_1", 10));
        // publisher_ = this->create_publisher<std_msgs::msg::String>("topic_1", 10);
        // robot_obj_.setPub(publisher_);
        // RCLCPP_INFO(this->get_logger(), "publisher_ use count= %ld", publisher_.use_count());
        RCLCPP_INFO(this->get_logger(), "robot_obj_ publisher use count= %d", robot_obj_.getPubUseCount());
    }

private:
    RobotObj robot_obj_{};
    rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_{};
};

int main(int argc, char **argv)
{
    // 初始化ros2的C++接口
    rclcpp::init(argc, argv);
    // 建立节点对象
    auto node = std::make_shared<PublisherNode>("publisher_01");
    // 运行节点，检测退出信号
    rclcpp::spin(node);
    // 销毁节点并关闭C++接口
    rclcpp::shutdown();

    return 0;
}